// 加载fs模块
const fs = require('fs');
// 加载path模块
const path = require('path');
// 加载express框架
const express = require('express');
// 创建应用服务
let app = express();
// 获取表单提交的数据
app.use(express.urlencoded({extended:false}));
// 读取persons.json文件
let persons = fs.readFileSync(__dirname+"/persons.json","utf8");
// console.log(persons);
// 转换persons.json文件格式
persons = JSON.parse(persons);
// console.log(persons);
// 登录渲染
app.get("/login",(req,res)=>{
    let urlpath = path.join(__dirname,"/view/login.html");
    let data = fs.readFileSync(urlpath);
    res.end(data);
})
// 注册渲染
app.get("/reg",(req,res)=>{
    let urlpath = path.join(__dirname,"/view/reg.html");
    let data = fs.readFileSync(urlpath);
    res.end(data);
})
// 登录接口
app.post("/login",(req,res)=>{
    let {username} = req.body;
    let {password} = req.body;
    let u = persons.find((item) => {
        return item.username == username && item.password == password;
    })
    if (u) {
        res.send("登录成功")
    } else {
        res.send("登录失败")
    }
})
// 注册接口
app.post("/reg",(req,res)=>{
    let {username} = req.body;
    let u = persons.findIndex((item) => {
        return item.username == username;
    })
    if (u == -1) {
        res.send("注册成功")
        persons.push(req.body)
    } else {
        res.send("用户名已被占用")
    }
})
// 监听端口
app.listen(5000,"127.0.0.1",()=>{
    console.log("启动服务"); 
})